package com.yuanfeng.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.base.OperationEntityVO;
import com.yuanfeng.commoms.vo.base.PlatformoperationVO;
import com.yuanfeng.commoms.vo.goods.GoodsDetailsListVO;
import com.yuanfeng.commoms.vo.shop.RetentionShopInfoVO;
import com.yuanfeng.commoms.vo.shop.ShopEvaluationVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.entity.OrderComplaintsEntity;
import com.yuanfeng.order.feign.BaseServiceClient;
import com.yuanfeng.order.mapper.OrderBaseMapper;
import com.yuanfeng.order.mapper.OrderComplaintsMapper;
import com.yuanfeng.order.mapper.OrderGoodsMapper;
import com.yuanfeng.order.service.OrderComplaintsService;
import com.yuanfeng.order.vo.SoldOrderByCommonalityDetailsVO;
import com.yuanfeng.order.vo.SoldOrderByGoodsDetailsVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName OrderComplaintsServiceImpl
 * @Description  用户投诉表
 * @Author cyp
 * @Date 2023-08-23 09:38:15
 * @Version 1.0
 **/
@Service
public class OrderComplaintsServiceImpl extends ServiceImpl<OrderComplaintsMapper, OrderComplaintsEntity>
        implements OrderComplaintsService {

    @Autowired
    private OrderBaseMapper orderBaseMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private BaseServiceClient baseServiceClient;

    @Override
    public ResponseResult addcomplaints(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String complaintsId = String.valueOf(map.get("complaintsId"));
        String userId = userInfo.getUserId();
        map.put("userId",userId);

        DateFormat dFormat4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (complaintsId == null || complaintsId == "") {
            //生成投诉单号
            StringBuffer id = new StringBuffer("TS");
            DateFormat dFormat3 = new SimpleDateFormat("yyyyMMdd");

            String format = dFormat3.format(new Date());

            Random random = new Random();
            String verificationCode = String.valueOf(random.nextInt(9) + 1);
            for (int i = 0; i < 5; i++) {
                verificationCode += random.nextInt(10);
            }
            id.append(format).append(verificationCode);
            map.put("complaintsId", id.toString());
        }
        map.put("complaintsStatus", 0);
        //投诉凭证
        List vouchers = (List) map.get("complaintsVouchers");
        String s = JSON.toJSONString(vouchers);
        map.put("complaintsVoucher",s);

        //投诉商品
        List goodsId = (List) map.get("goodsIds");
        String goodsIds = JSON.toJSONString(goodsId);
        map.put("complaintsGoodsid",goodsIds);

        //获取订单信息
        String orderId = String.valueOf(map.get("orderId"));
        SoldOrderByCommonalityDetailsVO sobcd = orderBaseMapper.soldOrderByCommonalityDetails(userId, orderId);

        if (map.get("complaintsType").equals(1)) {
            //投诉超时发货直接判定
            PlatformoperationVO queryplatform = queryplatform();
            if (queryplatform == null) {
                return ResponseResult.fail(0, "投诉失败");
            }
            //获取超时发货退款比例
            OperationEntityVO sendGoods = queryplatform.getSendGoods();

            //下单时间
            Date createTime = sobcd.getOrderCreateTime();
            //订单发货时间
            Date shippingTime = sobcd.getOrderShippingTime();
            //查询是否有超时商品
            List list = determinedeliverytime(userId, orderId, createTime, shippingTime);

            if (list != null && list.size() > 0) {
                //投诉成立  有超时发货订单
                map.put("complaintsStatus", 1);

                //计算退费金额
                BigDecimal multiply = calculateamount(sobcd.getOrderPaymentAmount(), sendGoods);
                map.put("compensationAmount", multiply);

                //获取商家质保金余额
                Integer selectshop = this.baseMapper.selectshop(sobcd.getShopId());
                BigDecimal bigDecimal = new BigDecimal(selectshop);
                if (bigDecimal.compareTo(new BigDecimal(0)) <= 0 || bigDecimal.compareTo(multiply) < 0) {
                    //质保金余额不足 暂不赔付
                    map.put("compensationStatus", 0);
                } else {
                    //进行赔付
                    Integer integer = determinedeliverytime2(userId, multiply,orderId);
                    if (integer == 1) {
                        //退款成功
                        map.put("compensationStatus", 1);
                    }

                    //修改商家质保金余额
                    //查询质保金信息
                    RetentionShopInfoVO selectretention = this.baseMapper.selectretention(sobcd.getShopId());
                    //质保金余额-
                    BigDecimal payPrice = selectretention.getRetentionMoneyBalance().subtract(multiply);

                    //质保金可提现
                    BigDecimal payPrice1 = payPrice.subtract(selectretention.getRetentionMoneyLimit());
                    if (payPrice1.compareTo(new BigDecimal(0)) == -1) {
                        payPrice1 = new BigDecimal(0);
                    }

                    //待补缴
                    BigDecimal payPrice2 = new BigDecimal(0);
                    if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) < 0) {
                        //待补缴金额
                        payPrice2 = selectretention.getRetentionMoneyPayment().add(multiply);
                        if (payPrice2.compareTo(new BigDecimal(0)) == -1) {
                            payPrice2 = new BigDecimal(0);
                        }
                    }

                    //累计赔付金额
                    BigDecimal payPrice3 = selectretention.getAccumulatedCompensation().add(multiply);
                    HashMap<Object, Object> paymap = new HashMap<>();
                    paymap.put("payPrice", payPrice);
                    paymap.put("payPrice1", payPrice1);
                    paymap.put("payPrice2", payPrice2);
                    paymap.put("payPrice3", payPrice3);
                    paymap.put("shopId", sobcd.getShopId());
                    if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) > 0){
                        paymap.put("retentionStatus",1);
                    }else if (payPrice.compareTo(new BigDecimal(0)) >= 0 && payPrice.compareTo(new BigDecimal(0)) == -1){
                        paymap.put("retentionStatus",2);

                        //发送站内信
                        String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
                        this.baseMapper.insertSysMessage1("",userId,"",5,
                                "补缴质保金",content, String.valueOf(sobcd.getShopId()));
                    }else if (payPrice.compareTo(new BigDecimal(0)) == -1){

                        //发送站内信
                        String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
                        this.baseMapper.insertSysMessage1("",userId,"",5,
                                "补缴质保金",content, String.valueOf(sobcd.getShopId()));
                        paymap.put("retentionStatus",3);
                        paymap.put("paymentTime", new Date());
                    }
                    //更新shopbase表
                    this.baseMapper.updateshopbase(paymap);
                }
            } else {
                //投诉不成立
                map.put("complaintsStatus", 2);
                map.put("compensationAmount", 0);
                map.put("compensationStatus", 1);
            }
        } else if (map.get("complaintsType").equals(2)) {
            //虚假发货
            PlatformoperationVO queryplatform = queryplatform();
            if (queryplatform == null) {
                return ResponseResult.fail(0, "投诉失败");
            }
            //获取修改发货配置
            OperationEntityVO falseShipment = queryplatform.getFalseShipment();

            //计算退费金额
            BigDecimal multiply = calculateamount(sobcd.getOrderPaymentAmount(), falseShipment);
            map.put("compensationAmount", multiply);

        } else if (map.get("complaintsType").equals(3)) {
            //违规出售
            PlatformoperationVO queryplatform = queryplatform();
            if (queryplatform == null) {
                return ResponseResult.fail(0, "投诉失败");
            }
            //获取违规出售罚款
            Integer multiply = queryplatform.getComplaintGoods();

            map.put("compensationAmount", multiply);

        } else if (map.get("complaintsType").equals(4)) {
            //骚扰辱骂
            PlatformoperationVO queryplatform = queryplatform();
            if (queryplatform == null) {
                return ResponseResult.fail(0, "投诉失败");
            }
            //获取骚扰辱骂罚款金额
            Integer multiply = queryplatform.getComplaintShop();

            map.put("compensationAmount", multiply);

        }
        map.put("shopId",sobcd.getShopId());
        map.put("fundDestination",1);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);
        map.put("failureTime",dFormat4.format(instance.getTime()));
        Integer integer = 0;
        Integer id = 0;
        map.put("id",0);
        if(complaintsId != null && complaintsId != ""){
            //更新投诉
            map.put("createTime",new Date());
            integer = this.baseMapper.updatecomplaints(map);
            id = (Integer) map.get("id");
        }else{
            map.put("createTime",new Date());

            integer = this.baseMapper.addcomplaints(map);
            id = (Integer) map.get("id");
        }

        if (integer > 0){
            return ResponseResult.success("投诉成功",id);
        }


        return  ResponseResult.fail(0, "投诉失败");
    }
    //查询平台管理规范
    public PlatformoperationVO queryplatform(){
        PlatformoperationVO platformoperation = new PlatformoperationVO();
        //查询平台管理规范
        String configValue = baseServiceClient.selectConfigValueFeign("platform_operation_specifications");
        if (configValue != null ){
            platformoperation = JSONObject.parseObject(configValue, PlatformoperationVO.class);
            return platformoperation;
        }
        return null;
    }
    //判断订单商品是否超时发货
    public List determinedeliverytime(String userId,String orderId,Date createTime,Date shippingTime){
        ArrayList<Map> list = new ArrayList<>();
        ArrayList commonid = new ArrayList<>();
        Date date = new Date();//当前时间
        Calendar instance = Calendar.getInstance();
        instance.setTime(createTime);//订单创建时间

        //获取商品信息
        List<SoldOrderByGoodsDetailsVO> sobgdList = orderBaseMapper.soldOrderByGoodsDetails(userId, orderId);
        if (sobgdList == null ){
            return list;
        }
        for (SoldOrderByGoodsDetailsVO soldOrderByGoodsDetails : sobgdList) {
            commonid.add(soldOrderByGoodsDetails.getCommonId());
        }
        if (commonid != null && commonid.size() > 0){
            List<Map> querydeliverytime = this.baseMapper.querydeliverytime(commonid);
            for (Map map : querydeliverytime) {
                Integer deliveryTime = (Integer) map.get("deliveryTime");

                instance.add(Calendar.HOUR,deliveryTime);
                //最后发货时间
                Date time = instance.getTime();
                if (shippingTime != null){
                    //已发货
                    int i = shippingTime.compareTo(time);
                    if (i > 0 ){
                        //超时发货订单
                        list.add(map);
                    }
                }else{
                    //未发货
                    int i = date.compareTo(time);
                    if (i > 0){
                        //超时发货订单
                        list.add(map);
                    }
                }
            }
        }
        return list;
    }
    //计算退费金额
    public BigDecimal calculateamount(BigDecimal paymentAmount, OperationEntityVO sendGoods){
        //计算赔付金额
        //退款百分比
        BigDecimal amount = BigDecimal.valueOf(sendGoods.getAmount());
        //最高可退
        BigDecimal highest = BigDecimal.valueOf(sendGoods.getHighest());
        //最低退
        BigDecimal minimum = BigDecimal.valueOf(sendGoods.getMinimum());
        //应退金额
        BigDecimal multiply = paymentAmount.multiply(amount.divide(new BigDecimal(100)));
        //大于最高可退
        if (multiply.compareTo(highest) > 0){
            multiply = highest;
        }
        //小于最低可退
        if (multiply.compareTo(minimum) < 0){
            multiply = minimum;
        }
        return multiply;
    }
    //有超时发货商品进行赔付
    @Transactional
    public Integer determinedeliverytime2(String userId,BigDecimal money,String orderId){
        Map<String,Object> assetDetailMap = new HashMap<>();
        Map<String,Object> ManageMoney = new HashMap<>();

        try {
            //退回用户余额
            assetDetailMap.put("detailType", 12);
            assetDetailMap.put("assetType", 1);
            assetDetailMap.put("assetAmount", money);
            assetDetailMap.put("assetDirection", "投诉退款");
            assetDetailMap.put("payType", 1);
            assetDetailMap.put("userId", userId);
            assetDetailMap.put("orderId", orderId);
            ManageMoney.put("money", money);
            ManageMoney.put("userId", userId);
            Integer integer = this.baseMapper.updateCardMemberDetailPort(ManageMoney);


            Integer integer1 = this.baseMapper.insertDetail(assetDetailMap);

            Map<String, Object> comRecord = new HashMap<String, Object>();
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
            String recordDate = dateformat.format(new Date());
            String[] reDate = recordDate.split("-");
            String year = reDate[0];
            String month = reDate[1];
            String day = reDate[2];
            String recordTitle = "投诉退款";
            String record_desc = "投诉退款";
            int tradeTypeId = 3;
            int userType = 1;
            int recordWithdraw = 0;
            double osCommisAmount = 0;
            double osCommisReturnAmount = 0;
            comRecord.put("recordDate", recordDate);
            comRecord.put("recordMoney", money);
            comRecord.put("orderId", money);
            comRecord.put("year", year);
            comRecord.put("month", month);
            comRecord.put("day", day);
            comRecord.put("plusOrMinus", 1);
            comRecord.put("recordTitle", recordTitle);
            comRecord.put("record_desc", record_desc);
            comRecord.put("tradeTypeId", tradeTypeId);
            comRecord.put("userType", userType);
            comRecord.put("recordWithdraw", recordWithdraw);
            comRecord.put("osCommisAmount", osCommisAmount);
            comRecord.put("osCommisReturnAmount", osCommisReturnAmount);
            comRecord.put("money", money);
            comRecord.put("userId", userId);
            //判断当前订单是否属于当前用户 1 是 2 否
            comRecord.put("isCurrentUser", 1);
            Integer integer2 = this.baseMapper.insertConsumeRecordport(comRecord);

            if (integer > 0 && integer1 > 0 && integer2 > 0){
                return 1;
            }
        }catch (Exception e){

        }
        return 2;
    }

    @Override
    public ResponseResult query(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String userId = userInfo.getUserId();

        String orderId = String.valueOf(map.get("orderId"));
        SoldOrderByCommonalityDetailsVO sobcd = orderBaseMapper.soldOrderByCommonalityDetails(userId, orderId);
        if (sobcd == null){
            return ResponseResult.fail(0, "订单信息有误",sobcd.getOrderStatus());
        }
        if (sobcd.getOrderStatus() == 1 || sobcd.getOrderStatus() == 7){
            return ResponseResult.success(1,"未超时发货",sobcd.getOrderStatus());
        }
        //下单时间
        Date createTime = sobcd.getOrderCreateTime();
        //订单发货时间
        Date shippingTime = sobcd.getOrderShippingTime();
        //查询是否有超时商品
        List list = determinedeliverytime(userId, orderId, createTime, shippingTime);
        if (list != null && list.size() > 0){
            return ResponseResult.success(1,"有超时发货",sobcd.getOrderStatus());
        }
        return ResponseResult.success(1,"未超时发货",sobcd.getOrderStatus());
    }

    @Override
    public ResponseResult isAfterSales(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String userId = userInfo.getUserId();

        String orderId = String.valueOf(map.get("orderId"));
        SoldOrderByCommonalityDetailsVO sobcd = orderBaseMapper.soldOrderByCommonalityDetails(userId, orderId);
        if (sobcd == null){
            return ResponseResult.fail(0, "订单信息有误");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String returnTime = sobcd.getOrderLastReturnTime();

        Date parse = null;
        if (returnTime != null) {
            try {
                parse = format.parse(returnTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            if (parse != null && parse.compareTo(new Date()) <= 0) {
                return ResponseResult.success(1,"该订单不在售后期",2);
            }
        }
        return ResponseResult.success(1,"在售后期",1);
    }

    @Override
    public ResponseResult isComplaints(Map<String, Object> map) {
        Integer integer = this.baseMapper.isComplaints(map);
        return ResponseResult.success(integer);
    }

    @Override
    public ResponseResult queryComplaints(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String userId = userInfo.getUserId();
        map.put("userId",userId);
        System.out.println(map);
        IPage<OrderComplaintsEntity> page = this.baseMapper.queryComplaints(new Query<OrderComplaintsEntity>().getPage(map),map);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult complaintsDetail(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String userId = userInfo.getUserId();
        map.put("userId",userId);

        OrderComplaintsEntity complaintsdetail = this.baseMapper.complaintsdetail(map);
        if (complaintsdetail != null){
            //凭证
            String complaintsVoucher = complaintsdetail.getComplaintsVoucher();
            List<String> list = JSON.parseArray(complaintsVoucher, String.class);
            complaintsdetail.setComplaintsVouchers(list);

            //商品id
            String complaintsGoodsid = complaintsdetail.getComplaintsGoodsid();
            List<Integer> list1 = JSON.parseArray(complaintsGoodsid, Integer.class);
            complaintsdetail.setComplaintsGoodsids(list1);

            if (list1 != null && list1.size() > 0){
                HashMap<String, Object> map1 = new HashMap<>();
                String orderId = complaintsdetail.getOrderId();
                if (orderId.startsWith("T")){
                    OrderComplaintsEntity orderComplaintsEntity = this.baseMapper.complaintsdetail(map);
                    complaintsdetail.setCorrelationComplaint(orderComplaintsEntity);
                }
                map1.put("orderId",orderId);
                map1.put("list",list1);
                List<GoodsDetailsListVO> orderGoods = orderGoodsMapper.queryComplaintsByGoodsList(map1);
                complaintsdetail.setGoods(orderGoods);
            }

            //卖家凭证
            String sellerVoucher = complaintsdetail.getSellerVoucher();
            List<String> list2 = JSON.parseArray(sellerVoucher, String.class);
            complaintsdetail.setSellerVouchers(list2);
        }
        return ResponseResult.success(complaintsdetail);
    }

    @Override
    public ResponseResult revokeComplaints(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (userInfo == null ){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String userId = userInfo.getUserId();
        Integer integer = this.baseMapper.revokeComplaints(userId, String.valueOf(map.get("complaintsId")));
        if (integer > 0){
            return ResponseResult.success(1,"撤销成功",1);
        }
        return ResponseResult.fail(2,"撤销失败",2);
    }

    @Override
    public ResponseResult queryComplaintsByPlatform(Map<String, Object> map) {
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        HashMap<Object, Object> hashMap = new HashMap<>();
        if (StringUtils.isEmpty(map.get("startTime"))){
            map.put("startTime",null);
        }
        if (StringUtils.isEmpty(map.get("endTime"))){
            map.put("endTime",null);
        }

        IPage<OrderComplaintsEntity> page=this.baseMapper.queryComplaintsByPlatform(new Query<OrderComplaintsEntity>().getPage(map),
                map);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryComplaintsDetailByPlatform(Map<String, Object> map) {
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        HashMap<Object, Object> hashMap = new HashMap<>();
        OrderComplaintsEntity querycomplaintsdetail = this.baseMapper.querycomplaintsdetail(map);
        if (querycomplaintsdetail != null) {
            String complaintsVoucher = querycomplaintsdetail.getComplaintsVoucher();
            List<String> strings = JSON.parseArray(complaintsVoucher, String.class);
            querycomplaintsdetail.setComplaintsVouchers(strings);

            String sellerVoucher = querycomplaintsdetail.getSellerVoucher();
            List<String> strings1 = JSON.parseArray(sellerVoucher, String.class);
            querycomplaintsdetail.setSellerVouchers(strings1);

            String goodsid = querycomplaintsdetail.getComplaintsGoodsid();
            List<Integer> list1 = JSON.parseArray(goodsid, Integer.class);
            querycomplaintsdetail.setComplaintsGoodsids(list1);
            if (list1 != null && list1.size() > 0){
                HashMap<String, Object> map1 = new HashMap<>();
                String orderId = querycomplaintsdetail.getOrderId();
                if (orderId.startsWith("T")){
                    OrderComplaintsEntity orderComplaintsEntity = this.baseMapper.querycomplaintsdetail1(orderId);
                    querycomplaintsdetail.setCorrelationComplaint(orderComplaintsEntity);
                }
                map1.put("orderId",orderId);
                map1.put("list",list1);
                List<GoodsDetailsListVO> orderGoods = this.baseMapper.queryGoodsList(map1);
                if (orderGoods != null && orderGoods.size() > 0){
                    for (GoodsDetailsListVO orderGood : orderGoods) {
                        Integer normalStatus = orderGood.getOrderStatus();
                        Integer orderRefundStatus = orderGood.getOrderRefundStatus();
                        Integer orderReturnStatus = orderGood.getOrderReturnStatus();
                        Integer status = orderGood.getOrderStatus();
                        if (normalStatus == 3 ) {
                            // 未发货状态
                            if (orderRefundStatus == 1 || orderRefundStatus == 3) {
                                // 未发货退款中
                                status = 22;
                            } else if (orderRefundStatus == 2) {
                                // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                                status = 26;
                            } else if (orderRefundStatus == 0 ) {
                                status = normalStatus;
                            } else{
                                status = 3;
                            }
                        } else if (normalStatus == 6) {
                            // 已完成状态
                            if (orderRefundStatus == 1 || orderRefundStatus == 3) {
                                // 收货退款中
                                status = 22;
                            } else if (orderRefundStatus == 2) {
                                status = 26;//收货退款完成
                            } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                                status = 6;//无退货退款
                            } else if (orderReturnStatus == 1 || orderReturnStatus == 3) {
                                //} else if (orderReturnStatus == 1 ) {
                                // 收货退货中
                                status = 24;
                            } else if (orderReturnStatus == 2) {
                                status = 25;//退货完成
                            } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                                status = 6;
                            }else{
                                status = 6;
                            }
                        } else {
                            status = normalStatus;
                        }
                        orderGood.setOrderStatus(status);
                    }
                }
                querycomplaintsdetail.setGoods(orderGoods);
            }
        }
        //查询店铺评分
        Integer shopId = querycomplaintsdetail.getShopId();
        ShopEvaluationVO see = this.baseMapper.ShopScore(shopId);
        if(see != null) {
            double add = 0;
            double servicecreditScore = see.getAvgServicecredit();
            double desccreditScore = see.getAvgDesccredit();
            double deliverycreditScore = see.getAvgDeliverycredit();
            if (String.valueOf(servicecreditScore) == null || see.getAvgServicecredit() == 0) {
                see.setEvaluationServicecredit(5);
                add = add + 5;
            } else {
                see.setEvaluationServicecredit(see.getAvgServicecredit());
                add = add + see.getAvgServicecredit();
            }
            if (String.valueOf(desccreditScore) == null || see.getAvgDesccredit() == 0) {
                see.setEvaluationDesccredit(5);
                add = add + 5;
            } else {
                see.setEvaluationDesccredit(see.getAvgDesccredit());
                add = add + see.getAvgDesccredit();
            }
            if (String.valueOf(deliverycreditScore) == null || see.getAvgDeliverycredit() == 0) {
                see.setEvaluationDeliverycredit(5);
                add = add + 5;
            } else {
                see.setEvaluationDeliverycredit(see.getAvgDeliverycredit());
                add = add + see.getAvgDeliverycredit();
            }
            BigDecimal two = new BigDecimal(add);
            double three = two.divide(new BigDecimal(3)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            hashMap.put("score",three);
        }else{
            hashMap.put("score",5);
        }
        //查询历史投诉单
        Integer integer = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderComplaintsEntity>()
                          .eq(OrderComplaintsEntity::getShopId,querycomplaintsdetail.getShopId()));
        if (integer == null){
            hashMap.put("historicalComplaints",0);
        }
        hashMap.put("historicalComplaints",integer);
        //查询历史申诉单
        Integer integer1 = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderComplaintsEntity>()
                           .eq(OrderComplaintsEntity::getShopId,querycomplaintsdetail.getShopId())
                           .eq(OrderComplaintsEntity::getIsAppeal, CommonType.commonStatus.YES.getCode()));
        if (integer1 == null){
            hashMap.put("historicalAppeal",0);
        }
        hashMap.put("historicalAppeal",integer1);

        hashMap.put("list",querycomplaintsdetail);
        return ResponseResult.success(hashMap);
    }

    @Override
    @GlobalTransactional
    public ResponseResult updateComplaint(Map<String, Object> map) {
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

        Integer status = (Integer) map.get("status");
        String amount1 = String.valueOf(map.get("amount"));
        String content = "";
        OrderComplaintsEntity querycomplaintsdetail = this.baseMapper.querycomplaintsdetail(map);
        if (querycomplaintsdetail == null){
            return ResponseResult.fail(0, "投诉单信息错误");
        }

        BigDecimal amount = new BigDecimal(querycomplaintsdetail.getCompensationAmount());

        //优先平台指定金额
        if (amount1 != null && amount1 != ""){
            amount = new BigDecimal(amount1);
        }

        Integer type = querycomplaintsdetail.getComplaintsType();
        if (type == 1){
            content = "扣款通知：您的店铺违反了【卖家未按时发货】规则将扣款" + amount + "元";
        }else if (type == 2){
            content = "扣款通知：您的店铺违反了【卖家虚假发货、缺货】规则将扣款" + amount + "元";
        }else if (type == 3){
            content = "扣款通知：您的店铺违反了【卖家违规出售商品、发布虚假商品信息】规则将扣款" + amount + "元";
        }else if (type == 4){
            content = "扣款通知：您的店铺违反了【卖家辱骂、骚扰、拉黑等】规则将扣款" + amount + "元";
        }else if (type == 5){
            content = "扣款通知：您的店铺违反了【售后退款】规则将扣款" + amount + "元";
        }

        if (status == 1){
            //投诉成立
            RetentionShopInfoVO selectretention = this.baseMapper.selectretention(querycomplaintsdetail.getShopId());
            //质保金余额
            BigDecimal balance = selectretention.getRetentionMoneyBalance();

            if (amount.compareTo(balance) > 0) {
                //质保金余额不足 暂不赔付
                map.put("compensationStatus", 0);
            } else {
                map.put("compensationStatus", 1);
                //将罚款转与消费者余额
                determinedeliverytime1(querycomplaintsdetail.getUserId(), amount, querycomplaintsdetail.getOrderId());

            }
            //修改质保金余额
            updateshopmoney(querycomplaintsdetail.getShopId(), amount);
            map.put("complaintsStatus",1);
            map.put("compensationAmount",amount);
            map.put("shopId",querycomplaintsdetail.getShopId());
            map.put("complaintsId",querycomplaintsdetail.getComplaintsId());
            this.baseMapper.handlingcomplaints(map);

            //发送短信通知
            this.baseMapper.insertSysMessage1(querycomplaintsdetail.getComplaintsId(),selectretention.getUserId(),"",5,
                    "申诉处理结果",content, String.valueOf(selectretention.getShopId()));
            return ResponseResult.success("处理成功");
        }else if (status == 2){
            //投诉不成立
            map.put("complaintsStatus",2);
            map.put("compensationAmount",amount);
            map.put("shopId",querycomplaintsdetail.getShopId());
            map.put("complaintsId",querycomplaintsdetail.getComplaintsId());
            this.baseMapper.handlingcomplaints(map);
            return ResponseResult.success("处理成功");
        }
        return ResponseResult.fail(0, "处理失败");
    }

    @Transactional
    public Integer determinedeliverytime1(String userId,BigDecimal money,String orderId){
        Map<String,Object> assetDetailMap = new HashMap<>();
        Map<String,Object> ManageMoney = new HashMap<>();

        //退回用户余额
        assetDetailMap.put("detailType", 12);
        assetDetailMap.put("assetType", 1);
        assetDetailMap.put("assetAmount", money);
        assetDetailMap.put("assetDirection", "投诉退款");
        assetDetailMap.put("payType", 1);
        assetDetailMap.put("userId", userId);
        assetDetailMap.put("orderId", orderId);
        ManageMoney.put("money", money);
        ManageMoney.put("userId", userId);
        Integer integer = this.baseMapper.updateCardMemberDetailPort(ManageMoney);


        Integer integer1 = this.baseMapper.insertDetail(assetDetailMap);

        Map<String, Object> comRecord = new HashMap<String, Object>();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        String recordDate = dateformat.format(new Date());
        String[] reDate = recordDate.split("-");
        String year = reDate[0];
        String month = reDate[1];
        String day = reDate[2];
        String recordTitle = "投诉退款";
        String record_desc = "投诉退款";
        int tradeTypeId = 3;
        int userType = 1;
        int recordWithdraw = 0;
        double osCommisAmount = 0;
        double osCommisReturnAmount = 0;
        comRecord.put("recordDate", recordDate);
        comRecord.put("recordMoney", money);
        comRecord.put("orderId", money);
        comRecord.put("year", year);
        comRecord.put("month", month);
        comRecord.put("day", day);
        comRecord.put("plusOrMinus", 1);
        comRecord.put("recordTitle", recordTitle);
        comRecord.put("record_desc", record_desc);
        comRecord.put("tradeTypeId", tradeTypeId);
        comRecord.put("userType", userType);
        comRecord.put("recordWithdraw", recordWithdraw);
        comRecord.put("osCommisAmount", osCommisAmount);
        comRecord.put("osCommisReturnAmount", osCommisReturnAmount);
        comRecord.put("money", money);
        comRecord.put("userId", userId);
        //判断当前订单是否属于当前用户 1 是 2 否
        comRecord.put("isCurrentUser", 1);
        Integer integer2 = this.baseMapper.insertConsumeRecordport(comRecord);

        if (integer > 0 && integer1 > 0 && integer2 > 0){
            return 1;
        }
        return 2;
    }


    //罚扣质保金
    @Transactional
    public Integer updateshopmoney(Integer shopId,BigDecimal amount){
        RetentionShopInfoVO selectretention = this.baseMapper.selectretention2(shopId);
        //质保金余额-
        BigDecimal payPrice = selectretention.getRetentionMoneyBalance().subtract(amount);
        //质保金可提现
        BigDecimal payPrice1 = payPrice.subtract(selectretention.getRetentionMoneyLimit());
        if (payPrice1.compareTo(new BigDecimal(0)) == -1) {
            payPrice1 = new BigDecimal(0);
        }

        //待补缴
        BigDecimal payPrice2 = new BigDecimal(0);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) < 0) {
            //待补缴金额  基础额度 - 余额
            payPrice2 = selectretention.getRetentionMoneyLimit().subtract(payPrice);
            if (payPrice2.compareTo(new BigDecimal(0)) == -1) {
                payPrice2 = new BigDecimal(0);
            }
        }

        //累计赔付金额
        BigDecimal payPrice3 = selectretention.getAccumulatedCompensation().add(amount);
        HashMap<Object, Object> paymap = new HashMap<>();
        paymap.put("payPrice", payPrice);
        paymap.put("payPrice1", payPrice1);
        paymap.put("payPrice2", payPrice2);
        paymap.put("payPrice3", payPrice3);
        paymap.put("shopId", shopId);
        if (payPrice.compareTo(selectretention.getRetentionMoneyLimit()) >= 0) {
            paymap.put("retentionStatus", 1);
        } else if (payPrice.compareTo(new BigDecimal(0)) >= 0 && payPrice2.compareTo(new BigDecimal(0)) > 0) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            this.baseMapper.insertSysMessage1("",selectretention.getUserId(),"",5,
                    "补缴质保金",content, String.valueOf(selectretention.getShopId()));

            paymap.put("retentionStatus", 2);
        } else if (payPrice.compareTo(new BigDecimal(0)) == -1) {
            //发送站内信
            String content = "亲爱的卖家您好，根据平台质保金规则您需补缴" + payPrice2 + " 元质保金，请登录商家后台查询。";
            this.baseMapper.insertSysMessage1("",selectretention.getUserId(),"",5,
                    "补缴质保金",content, String.valueOf(selectretention.getShopId()));

            paymap.put("retentionStatus", 3);
            paymap.put("paymentTime", new Date());
        }
        //更新shopbase表
        if(selectretention.getRetentionStatus() == 3){
            paymap.put("paymentTime", null);
        }
        return  this.baseMapper.updateshopbase(paymap);
    }

}
